<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-xm.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-xm.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="QQ聊天机器人-教程向这篇文章将引导大家如何去写一个QQ聊天机器人。在此之前，先给大伙儿展示一下本fw的Robot的一些特点和功能：   Name: Arina Attribute: 萌妹子 官网：http://47.98.252.1:7000/arina">
<meta property="og:type" content="article">
<meta property="og:title" content="QQ聊天机器人">
<meta property="og:url" content="http://yoursite.com/2020/05/30/QQ聊天机器人/index.html">
<meta property="og:site_name" content="Ming">
<meta property="og:description" content="QQ聊天机器人-教程向这篇文章将引导大家如何去写一个QQ聊天机器人。在此之前，先给大伙儿展示一下本fw的Robot的一些特点和功能：   Name: Arina Attribute: 萌妹子 官网：http://47.98.252.1:7000/arina">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8i163zbj30aa08wglu.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gga0qsbw9ij30hr0crq3c.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8lxa5h7j30mf03z3ye.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8mred9wj30mz056mx3.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8nrobwvj30m904p3yf.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8pfypwbj30mn04wdfp.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrpsbldcj314h0bst9i.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrpbwgbej315h09zt97.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrqpxet3j30kw0mvjs5.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8t1l9j5j30k20powg8.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrr7lvmvj30eh03gt8m.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gga0x84659j30js04raa1.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gga0wtd3u1j30li04zglm.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gga11ttyf0j30ut04baab.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrsncyjjj30cg0ixtaf.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggw782eeoxj30lx04baa3.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggw786pk9hj30mg04m0sq.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggw7926em0j30m3041q2v.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggw7gwizxbj30m108l0tb.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrtglt2rj31hc0u0aco.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gga1tchswdj31hc0ssmxz.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gga1xl84ytj31hc0swmza.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs1i133ij30xm0nq76j.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs27mwbdj30xl0nbgnk.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs2x2llsj30x50i63zf.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs2x2llsj30x50i63zf.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8s8hx0qj30lp040t8t.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrqpxet3j30kw0mvjs5.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs81bdm5j30h00ahwf4.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjsa2hxbvj30xd0nkdhh.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1ggjsaggqloj30wl0fpwg1.jpg">
<meta property="og:updated_time" content="2020-08-25T01:56:37.397Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="QQ聊天机器人">
<meta name="twitter:description" content="QQ聊天机器人-教程向这篇文章将引导大家如何去写一个QQ聊天机器人。在此之前，先给大伙儿展示一下本fw的Robot的一些特点和功能：   Name: Arina Attribute: 萌妹子 官网：http://47.98.252.1:7000/arina">
<meta name="twitter:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8i163zbj30aa08wglu.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/05/30/QQ聊天机器人/">





  <title>QQ聊天机器人 | Ming</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2ff12830577cde1e94dd80bdcf083398";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ming</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            Commonweal 404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/30/QQ聊天机器人/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ming">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/arina.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ming">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">QQ聊天机器人</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-05-30T09:39:14+08:00">
                2020-05-30
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Fun/" itemprop="url" rel="index">
                    <span itemprop="name">Fun</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  5.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Reading time &asymp;</span>
                
                <span title="Reading time">
                  25
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="QQ聊天机器人-教程向"><a href="#QQ聊天机器人-教程向" class="headerlink" title="QQ聊天机器人-教程向"></a>QQ聊天机器人-教程向</h1><p>这篇文章将引导大家如何去写一个QQ聊天机器人。在此之前，先给大伙儿展示一下本fw的Robot的一些特点和功能：</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8i163zbj30aa08wglu.jpg">

<p>Name: Arina</p>
<p>Attribute: 萌妹子</p>
<p>官网：<a href="http://47.98.252.1:7000/arina" target="_blank" rel="noopener">http://47.98.252.1:7000/arina</a></p>
<a id="more"></a>

<h2 id="功能："><a href="#功能：" class="headerlink" title="功能："></a>功能：</h2><h4 id="发送以-为前缀的消息可以触发图灵机器人的功能，这些功能包含但不限于："><a href="#发送以-为前缀的消息可以触发图灵机器人的功能，这些功能包含但不限于：" class="headerlink" title="发送以#为前缀的消息可以触发图灵机器人的功能，这些功能包含但不限于："></a>发送以#为前缀的消息可以触发图灵机器人的功能，这些功能包含但不限于：</h4><ul>
<li>天气查询<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gga0qsbw9ij30hr0crq3c.jpg"></li>
<li>数学运算<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8lxa5h7j30mf03z3ye.jpg"></li>
<li>聊天对话<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8mred9wj30mz056mx3.jpg"></li>
<li>单词翻译<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8nrobwvj30m904p3yf.jpg"></li>
</ul>
<h4 id="不需要-前缀能对一些特定的语句做出反应"><a href="#不需要-前缀能对一些特定的语句做出反应" class="headerlink" title="不需要#前缀能对一些特定的语句做出反应"></a>不需要#前缀能对一些特定的语句做出反应</h4><img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8pfypwbj30mn04wdfp.jpg">



<h4 id="可以在群里-其他人或者禁言（需要管理员权限）"><a href="#可以在群里-其他人或者禁言（需要管理员权限）" class="headerlink" title="可以在群里@其他人或者禁言（需要管理员权限）"></a>可以在群里@其他人或者禁言（需要管理员权限）</h4><h4 id><a href="#" class="headerlink" title></a><img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrpsbldcj314h0bst9i.jpg"></h4><h4 id="可以通过接口向指定的群手动发送消息"><a href="#可以通过接口向指定的群手动发送消息" class="headerlink" title="可以通过接口向指定的群手动发送消息"></a>可以通过接口向指定的群手动发送消息</h4><img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrpbwgbej315h09zt97.jpg">

<h4 id="定时天气播报"><a href="#定时天气播报" class="headerlink" title="定时天气播报"></a>定时天气播报</h4><p>每天早上8点准时向qq群播送今日天气状况，误差小于2秒。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrqpxet3j30kw0mvjs5.jpg">

<h4 id="定时晚安"><a href="#定时晚安" class="headerlink" title="定时晚安"></a>定时晚安</h4><p>每晚12点，可以从指定的文件里随机抽取一行向qq群发送晚安。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8t1l9j5j30k20powg8.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrr7lvmvj30eh03gt8m.jpg">



<h4 id="记录清醒时长"><a href="#记录清醒时长" class="headerlink" title="记录清醒时长"></a>记录清醒时长</h4><p>回复“zao”或“wan”可以触发功能。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gga0x84659j30js04raa1.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gga0wtd3u1j30li04zglm.jpg">

<h4 id="疫情数据查询"><a href="#疫情数据查询" class="headerlink" title="疫情数据查询"></a>疫情数据查询</h4><p>回复关键字 “疫情数据 area”可以触发功能，栗子：<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gga11ttyf0j30ut04baab.jpg"></p>
<h4 id="复读机"><a href="#复读机" class="headerlink" title="复读机"></a>复读机</h4><p>回复关键字“进入复读模式”、“关闭复读模式”可以触发功能。</p>
<p>Arina会重复你说的话。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrsncyjjj30cg0ixtaf.jpg">

<h4 id="彩虹屁"><a href="#彩虹屁" class="headerlink" title="彩虹屁"></a>彩虹屁</h4><p>回复关键字“夸xx”即可触发。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggw782eeoxj30lx04baa3.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggw786pk9hj30mg04m0sq.jpg">

<h4 id="NMSL"><a href="#NMSL" class="headerlink" title="NMSL"></a>NMSL</h4><p>回复关键字“骂xx”即可触发。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggw7926em0j30m3041q2v.jpg">

<h4 id="学习"><a href="#学习" class="headerlink" title="学习"></a>学习</h4><p>回复关键字“跟我学 XX YY”即可触发。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggw7gwizxbj30m108l0tb.jpg">

<h4 id="Arina的个人页面"><a href="#Arina的个人页面" class="headerlink" title="Arina的个人页面"></a>Arina的个人页面</h4><img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrtglt2rj31hc0u0aco.jpg">

<p>现在页面还很简陋，功能也比较少，以后会添加更多有意思的功能。</p>
<h2 id="需要的技能或工具："><a href="#需要的技能或工具：" class="headerlink" title="需要的技能或工具："></a>需要的技能或工具：</h2><ul>
<li>服务器一个（如果你想让robot 24小时在线）</li>
<li>QQ小号一个</li>
<li>精通java（的拼写）</li>
<li>对Http有所了解</li>
<li>会使用java向服务器指定的端口发送GET请求</li>
<li>会使用java对文件进行读取操作</li>
<li><del>会使用java创建线程（定时推送时所需）</del></li>
<li>掌握linux常用命令若干（可以随时百度）</li>
<li>会使用maven进行依赖管理和打包部署</li>
<li>会JSON和JavaBean的相互转换（调天气查询api以及疫情数据api时所需）</li>
<li>会使用Spring Boot编写web服务器（接受cqhttp插件的post请求以及对robot页面的get请求）</li>
<li>会使用html+css+JavaScript+jquery+bootstrap（写页面时所需）</li>
<li>会使用一种模板引擎（比如ThymeLeaf，前后端交互所需）</li>
<li>图灵机器人（可以去官网免费领取）</li>
<li><u>不抛弃、不放弃（坑实在太多了）</u></li>
</ul>
<h2 id="本项目基于："><a href="#本项目基于：" class="headerlink" title="本项目基于："></a>本项目基于：</h2><ul>
<li>酷Q</li>
<li>酷Q插件：CQHTTP（酷Q本身使用易语言编写的，这就对不熟悉易语言的人造成很大障碍，这个插件通过 HTTP 对 酷Q 的事件进行上报以及接收 HTTP 请求来调用 酷Q 的 DLL 接口，从而可以使用其它语言编写 酷Q 插件。现已支持 WebSocket。不得不说，这是个绝妙的注意。</li>
<li>java</li>
<li>Spring Boot</li>
</ul>
<h2 id="本fw使用的开发平台："><a href="#本fw使用的开发平台：" class="headerlink" title="本fw使用的开发平台："></a>本fw使用的开发平台：</h2><ul>
<li><p>全宇宙第一的Intellij IDEA 2020</p>
</li>
<li><p>Edge浏览器</p>
</li>
</ul>
<p><del>还有好多作业没做，等我做完在更（逃</del></p>
<h2 id="酷q和cqhttp介绍"><a href="#酷q和cqhttp介绍" class="headerlink" title="酷q和cqhttp介绍"></a>酷q和cqhttp介绍</h2><h3 id="酷q"><a href="#酷q" class="headerlink" title="酷q"></a>酷q</h3><p>酷q是类似qq客户端的一个软件，提供了许多基本的功能（发送接收消息，群管理等）。酷q本身提供了一些功能（自动回复，图灵机器人插件），但这些功能仍然比较匮乏，想要增加新的功能，就需要编写酷q插件。但是编写酷q插件需要用到易语言，因此像我这种不会易语言的就变得束手无策。</p>
<h3 id="cqhttp"><a href="#cqhttp" class="headerlink" title="cqhttp"></a>cqhttp</h3><p>cqhttp是酷q的一个插件，这个插件通过 HTTP 对 酷Q 的事件进行上报以及接收 HTTP 请求来调用 酷Q 的 DLL 接口，从而可以使用其它语言编写 酷Q 插件。于是，我就可以用java来实现我想要的功能了。</p>
<h2 id="购买服务器"><a href="#购买服务器" class="headerlink" title="购买服务器"></a>购买服务器</h2><p>Arina需要在一个24小时不关机的电脑上运行，如果愿意自己的电脑永远不关机，也可以不需要服务器。</p>
<p>服务器可以上阿里云买最便宜的，能用就行。</p>
<p>可以不用域名（域名备案很麻烦），直接通过ip地址访问服务器。</p>
<h2 id="服务器开放端口"><a href="#服务器开放端口" class="headerlink" title="服务器开放端口"></a>服务器开放端口</h2><p>比如我的NoVNC运行在服务器的9000端口下，我需要修改安全组策略，对9000端口“放行”。<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gga1tchswdj31hc0ssmxz.jpg"></p>
<p>如何修改安全组策略取决于你的服务器供应商，请自行百度。</p>
<h2 id="酷q在linux环境下的运行"><a href="#酷q在linux环境下的运行" class="headerlink" title="酷q在linux环境下的运行"></a>酷q在linux环境下的运行</h2><p>酷q在windows下可以简单的安装运行，但在linux下需要通过wine借助docker来运行。</p>
<p>基本用法：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">$ docker pull richardchien/cqhttp:latest</span><br><span class="line">$ mkdir coolq  <span class="comment"># 用于存储 酷Q 的程序文件</span></span><br><span class="line">$ docker run -ti --rm --name cqhttp-test \</span><br><span class="line">             -v $(<span class="built_in">pwd</span>)/coolq:/home/user/coolq \  <span class="comment"># 将宿主目录挂载到容器内用于持久化 酷Q 的程序文件</span></span><br><span class="line">             -p 9000:9000 \  <span class="comment"># noVNC 端口，用于从浏览器控制 酷Q</span></span><br><span class="line">             -p 5700:5700 \  <span class="comment"># CQHTTP 插件开放的端口</span></span><br><span class="line">             -e COOLQ_ACCOUNT=123456 \ <span class="comment"># 要登录的 QQ 账号，可选但建议填</span></span><br><span class="line">             -e CQHTTP_POST_URL=http://example.com:8080 \  <span class="comment"># 事件上报地址</span></span><br><span class="line">             -e CQHTTP_SERVE_DATA_FILES=yes \  <span class="comment"># 允许通过 HTTP 接口访问 酷Q 数据文件</span></span><br><span class="line">             richardchien/cqhttp:latest</span><br></pre></td></tr></table></figure>

<p>这部分请参考</p>
<ul>
<li><a href="https://github.com/CoolQ/docker-wine-coolq（原版镜像）" target="_blank" rel="noopener">https://github.com/CoolQ/docker-wine-coolq（原版镜像）</a></li>
<li><a href="https://cqhttp.cc/docs/4.15/#/Docker（安装了cqhttp插件的镜像）" target="_blank" rel="noopener">https://cqhttp.cc/docs/4.15/#/Docker（安装了cqhttp插件的镜像）</a></li>
</ul>
<h2 id="获取并配置图灵机器人api-key"><a href="#获取并配置图灵机器人api-key" class="headerlink" title="获取并配置图灵机器人api key"></a>获取并配置图灵机器人api key</h2><p>上官网<a href="http://www.turingapi.com/注册领取。" target="_blank" rel="noopener">http://www.turingapi.com/注册领取。</a></p>
<p>获取到之后手动添加到酷q的图灵机器人插件里：</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gga1xl84ytj31hc0swmza.jpg">

<p>图灵机器人本身有丰富的功能，免费版的api调用次数有限制。到此为止，robot就像模像样了。根据我的体验，这个图灵机器人并不是很智能，有时候像个智障，远远不及小爱同学或者cortana，但毕竟是免费的。</p>
<h2 id="核心：cqhttp插件的使用（java）"><a href="#核心：cqhttp插件的使用（java）" class="headerlink" title="核心：cqhttp插件的使用（java）"></a>核心：cqhttp插件的使用（java）</h2><h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p>使用cqhttp，可以手动给酷q安装插件，也可以用作者预先配置好的镜像直接运行docker。这部分内容请参考cqhttp的官方文档：<a href="https://cqhttp.cc/docs/4.15/#/。" target="_blank" rel="noopener">https://cqhttp.cc/docs/4.15/#/。</a></p>
<p>注意留心cqhttp插件上报事件的端口。</p>
<h3 id="API"><a href="#API" class="headerlink" title="API"></a>API</h3><img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs1i133ij30xm0nq76j.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs27mwbdj30xl0nbgnk.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs2x2llsj30x50i63zf.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs2x2llsj30x50i63zf.jpg">

<h3 id="发送qq消息"><a href="#发送qq消息" class="headerlink" title="发送qq消息"></a>发送qq消息</h3><p>cqhttp插件可以监听指定端口的事件，我们需要根据想要发送的内容拼接url，向服务器的指定端口发送get请求。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.URI;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpRequest;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpResponse;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Utils</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Utils.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sendGroupMessage</span><span class="params">(String message)</span> <span class="keyword">throws</span> URISyntaxException, IOException, InterruptedException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正准备构造HttpRequest"</span>);</span><br><span class="line">        String url = String.format(<span class="string">"http://47.98.252.1:5700/send_group_msg?group_id=549594617&amp;message=%s"</span>, message.replace(<span class="string">" "</span>, <span class="string">"%20"</span>).replace(<span class="string">"\n"</span>, <span class="string">"%0a"</span>));<span class="comment">// main:549594617 测试群：851736129</span></span><br><span class="line">        log.info(<span class="string">"构造好的url：&#123;&#125;"</span>, url);</span><br><span class="line">        HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">                .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">                .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">                .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">                .version(HttpClient.Version.HTTP_2)</span><br><span class="line">                .build();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正准备用Http Client向服务器发送get请求"</span>);</span><br><span class="line">        httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>url中，group_id参数是群号或者qq号，message参数是想要发送的内容。上面是用java编写的构造url并利用httpClient向服务器的5700（端口取决于自己的设置）端口发送get请求的代码。</p>
<p>拼接url参数的时候，注意空格、换行符以及特殊字符的转义，比如空格在url里是%20，换行符在url里是%0a，否则会出现异常（比如发送的内容不能含有空格）。</p>
<p>注意服务器的安全组策略，需要开放指定的端口才行（我这儿是5700）。</p>
<h3 id="禁言群用户"><a href="#禁言群用户" class="headerlink" title="禁言群用户"></a>禁言群用户</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.URI;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpRequest;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpResponse;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Utils</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Utils.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setGroupBan</span><span class="params">(<span class="keyword">long</span> userId, <span class="keyword">int</span> duration)</span> <span class="keyword">throws</span> URISyntaxException, IOException, InterruptedException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在准备构造HttpRequest"</span>);</span><br><span class="line">        String url = String.format(<span class="string">"http://47.98.252.1:5700/set_group_ban?group_id=549594617&amp;user_id=%d&amp;duration=%d"</span>, userId, duration);</span><br><span class="line">        HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">                .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">                .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">                .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">                .version(HttpClient.Version.HTTP_2)</span><br><span class="line">                .build();</span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正准备用Http Client向服务器发送get请求"</span>);</span><br><span class="line">        httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这其实和发送qq消息的过程一样，只是url的参数有所不同。需要设置群号，qq号和禁言的时间。</p>
<h3 id="定时发送消息"><a href="#定时发送消息" class="headerlink" title="定时发送消息"></a>定时发送消息</h3><p>起初我的实现思路是新创建一个线程，不停地判断当前的时间，等到指定的时间再执行相关的代码。</p>
<p>后来我遇到一些我无法解决问题，把整个项目用spring重新组织了一遍。</p>
<p>用了spring之后，事情就变得简单起来了，定时发送消息可以通过spring的注解<code>@Scheduled(fixedRate = 1000)</code>实现。</p>
<p>栗子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scheduled</span>(fixedRate = <span class="number">1000</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">resetMapAndIndex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    LocalDateTime now = LocalDateTime.now();</span><br><span class="line">    <span class="keyword">if</span> (now.getHour() == <span class="number">3</span> &amp;&amp; now.getMinute() == <span class="number">0</span> &amp;&amp; now.getSecond() == <span class="number">0</span>) &#123;</span><br><span class="line">        log.info(<span class="string">"凌晨三点整，正在重置map和index"</span>);</span><br><span class="line">        map.clear();</span><br><span class="line">        index = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个方法每隔一秒执行一次，判断时间再执行相应的操作就可以达成目的。</p>
<h3 id="定时晚安功能"><a href="#定时晚安功能" class="headerlink" title="定时晚安功能"></a>定时晚安功能</h3><p>如果是每天都不变的一句话，未免过于单调了。可以从以下文本中随机抽取一行作为今晚要发送的消息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">要想身体好，睡觉不蒙脑。</span><br><span class="line">早睡早起，没病惹你。</span><br><span class="line">早睡早起，清爽欢喜;迟睡迟起，强拉眼皮。</span><br><span class="line">早睡早起，赛过人参补身体。</span><br><span class="line">早睡早起拥有健康生活。</span><br><span class="line">睡眠好身体才好。</span><br><span class="line">睡前洗脚，胜吃补药。</span><br><span class="line">晚餐少喝水，睡前不饮茶。</span><br><span class="line">晚上开窗，一夜都香。</span><br><span class="line">开启心灵之窗，共同关注睡眠。</span><br><span class="line">科学管理睡眠。</span><br><span class="line">瞌睡没根，越睡越深。</span><br><span class="line">良好睡眠、健康人生。</span><br><span class="line">培养良好睡眠习惯，保持健康生活方式。</span><br><span class="line">食不多言，寝不多语。</span><br><span class="line">适当吃睡，无病增岁。</span><br><span class="line">科学享睡，健康无病。</span><br><span class="line">不觅仙方觅睡方。</span><br><span class="line">吃罢中饭睡一觉，健健康康活到老。</span><br><span class="line">吃洋参，不如睡五更。</span><br><span class="line">坐有坐相，睡有睡相，睡觉要像弯月亮。</span><br><span class="line">坐有坐相，睡有睡相，睡觉要像弯月亮。</span><br><span class="line">科学享睡，健康无病。</span><br><span class="line">不觅仙方觅睡方。</span><br><span class="line">吃罢中饭睡一觉，健健康康活到老。</span><br><span class="line">吃洋参，不如睡五更。</span><br><span class="line">吃药十付，不如独宿一夜。</span><br><span class="line">充足睡眠，身心健康。</span><br><span class="line">关注睡眠障碍，提倡科学睡眠。</span><br><span class="line">合理安排生活，拥有健康睡眠。</span><br><span class="line">健康生活，良好睡眠。</span><br><span class="line">今天的沉睡成就明天的活力。</span><br><span class="line">开启心灵之窗，共同关注睡眠。</span><br><span class="line">科学管理睡眠。</span><br><span class="line">瞌睡没根，越睡越深。</span><br><span class="line">良好睡眠、健康人生。</span><br><span class="line">培养良好睡眠习惯，保持健康生活方式。</span><br><span class="line">食不多言，寝不多语。</span><br><span class="line">适当吃睡，无病增岁。</span><br><span class="line">适度少睡眠，可以保长寿。</span><br><span class="line">睡出健康来。</span><br><span class="line">睡觉不蒙头，活到九十九。</span><br><span class="line">睡眠，健康的选择。</span><br></pre></td></tr></table></figure>

<p>思路是生成一个指定范围内的随机数作为行数，读取指定行的内容并定时发送。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.scheduling.annotation.Scheduled;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.time.LocalDateTime;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodNight</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(GoodNight.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getWords</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在尝试从文本文件里随机抽取一行作为晚安语录"</span>);</span><br><span class="line">        InputStream inputStream = getClass().getResourceAsStream(<span class="string">"/goodNight.txt"</span>);</span><br><span class="line">        Reader reader = <span class="keyword">new</span> InputStreamReader(inputStream, StandardCharsets.UTF_8);</span><br><span class="line">        BufferedReader bufferedReader = <span class="keyword">new</span> BufferedReader(reader);</span><br><span class="line">        <span class="comment">//文件有43行</span></span><br><span class="line">        <span class="keyword">int</span> line = ((<span class="keyword">int</span>) (Math.random() * <span class="number">100</span>)) % <span class="number">43</span> + <span class="number">1</span>;</span><br><span class="line">        String ans = <span class="string">""</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; line; i++) &#123;</span><br><span class="line">            ans = bufferedReader.readLine();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> ans + <span class="string">"大家晚安＜(▰˘◡˘▰)"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">broadcastGoodNight</span><span class="params">()</span> <span class="keyword">throws</span> IOException, InterruptedException, URISyntaxException </span>&#123;</span><br><span class="line">        String words = getWords();</span><br><span class="line">        Utils.sendGroupMessage(words);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Scheduled</span>(fixedRate = <span class="number">1000</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">broadcast</span><span class="params">()</span> <span class="keyword">throws</span> IOException, InterruptedException, URISyntaxException </span>&#123;</span><br><span class="line">        LocalDateTime now = LocalDateTime.now();</span><br><span class="line">        <span class="keyword">if</span> (now.getHour() == <span class="number">0</span> &amp;&amp; now.getMinute() == <span class="number">0</span> &amp;&amp; now.getSecond() == <span class="number">0</span>) &#123;</span><br><span class="line">            log.info(<span class="string">"晚上24点整，正准备播报晚安"</span>);</span><br><span class="line">            broadcastGoodNight();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="定时天气播报-1"><a href="#定时天气播报-1" class="headerlink" title="定时天气播报"></a>定时天气播报</h3><p>首先需要一个高德地图查询天气的api，可以去官网免费申请。向这个api发送get请求可以得到想要的天气数据。</p>
<p>返回的天气数据是json模样的字符串，我们需要把字符串转为java bean，这样操作起来更方便，因此需要准备一个接受数据的java bean：Weather。我这里java bean和定时发送的代码写在了一起。</p>
<p>得到java bean之后，就可以定时发送天气情况了。</p>
<h4 id="旧版本代码"><a href="#旧版本代码" class="headerlink" title="旧版本代码"></a>旧版本代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot.weather;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.DeserializationFeature;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> eternal.fire.springbootrobot.Utils;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.scheduling.annotation.Scheduled;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.URI;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpRequest;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpResponse;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"><span class="keyword">import</span> java.time.LocalDateTime;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Weather</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> String status;</span><br><span class="line">    <span class="keyword">public</span> String count;</span><br><span class="line">    <span class="keyword">public</span> String info;</span><br><span class="line">    <span class="keyword">public</span> String infocode;</span><br><span class="line">    <span class="keyword">public</span> List&lt;Live&gt; lives;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Weather.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">generateString</span><span class="params">(HttpClient httpClient)</span> <span class="keyword">throws</span> IOException, InterruptedException, URISyntaxException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在通过高德api获取西峰区天气状况，结果将以字符串形式返回给调用函数"</span>);</span><br><span class="line">        log.info(<span class="string">"构造HttpRequest"</span>);</span><br><span class="line">        String url = <span class="string">"https://restapi.amap.com/v3/weather/weatherInfo?key=b74ab54158c425e0ddbe4db7dce8624b&amp;city=621002"</span>;</span><br><span class="line">        HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">                .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">                .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">                .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">                .version(HttpClient.Version.HTTP_2)</span><br><span class="line">                .build();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在通过http client发送构造好的HttpRequest，并获得天气查询结果"</span>);</span><br><span class="line">        HttpResponse&lt;String&gt; httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在将查询到的天气json转化为Java Bean"</span>);</span><br><span class="line">        String json = httpResponse.body();</span><br><span class="line">        ObjectMapper mapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, <span class="keyword">false</span>);</span><br><span class="line">        Weather weather = mapper.readValue(json, Weather.class);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在准备拼接字符串"</span>);</span><br><span class="line">        Live live = weather.lives.get(<span class="number">0</span>);</span><br><span class="line">        String result = <span class="string">"今日天气预报来啦~++++播报时间:"</span> + live.reporttime + <span class="string">"++++省份："</span> + live.province + <span class="string">"++++城市："</span> + live.city + <span class="string">"++++天气："</span> + live.weather</span><br><span class="line">                + <span class="string">"++++温度："</span> + live.temperature</span><br><span class="line">                + <span class="string">"++++风向："</span> + live.winddirection + <span class="string">"++++风力："</span> + live.windpower + <span class="string">"++++湿度："</span> + live.humidity;</span><br><span class="line">        result = result.replaceAll(<span class="string">" "</span>, <span class="string">"+"</span>);</span><br><span class="line">        log.info(<span class="string">"拼接完毕，结果：&#123;&#125;"</span>, result);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">broadcastWeather</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, IOException, URISyntaxException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正准备向群里播报天气"</span>);</span><br><span class="line">        log.info(<span class="string">"获得天气状况（字符串）"</span>);</span><br><span class="line">        String result = generateString(httpClient);</span><br><span class="line">        Utils.sendGroupMessage(result);</span><br><span class="line">        log.info(<span class="string">"播报完毕"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Scheduled</span>(fixedRate = <span class="number">1000</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">broadcast</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, IOException, URISyntaxException </span>&#123;</span><br><span class="line">        LocalDateTime now = LocalDateTime.now();</span><br><span class="line">        <span class="keyword">if</span> (now.getHour() == <span class="number">8</span> &amp;&amp; now.getMinute() == <span class="number">0</span> &amp;&amp; now.getSecond() == <span class="number">0</span>) &#123;</span><br><span class="line">            log.info(<span class="string">"早上八点整，正准备播报天气"</span>);</span><br><span class="line">            broadcastWeather();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="新版本代码"><a href="#新版本代码" class="headerlink" title="新版本代码"></a>新版本代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot.weather;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.DeserializationFeature;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> eternal.fire.springbootrobot.Utils;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.scheduling.annotation.Scheduled;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.URI;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpRequest;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpResponse;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"><span class="keyword">import</span> java.time.LocalDateTime;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Weather</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Weather.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line">    <span class="keyword">private</span> String status;</span><br><span class="line">    <span class="keyword">private</span> String count;</span><br><span class="line">    <span class="keyword">private</span> String info;</span><br><span class="line">    <span class="keyword">private</span> String infocode;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Forecasts&gt; forecasts;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getStatus</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> status;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setStatus</span><span class="params">(String status)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.status = status;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCount</span><span class="params">(String count)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.count = count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getInfo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> info;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setInfo</span><span class="params">(String info)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.info = info;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getInfocode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> infocode;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setInfocode</span><span class="params">(String infocode)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.infocode = infocode;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Forecasts&gt; <span class="title">getForecasts</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> forecasts;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setForecasts</span><span class="params">(List&lt;Forecasts&gt; forecasts)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.forecasts = forecasts;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">generateString</span><span class="params">(HttpClient httpClient)</span> <span class="keyword">throws</span> IOException, InterruptedException, URISyntaxException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在通过高德api获取西峰区天气状况，结果将以字符串形式返回给调用函数"</span>);</span><br><span class="line">        log.info(<span class="string">"构造HttpRequest"</span>);</span><br><span class="line">        String url = <span class="string">"https://restapi.amap.com/v3/weather/weatherInfo?key=b74ab54158c425e0ddbe4db7dce8624b&amp;city=621002&amp;extensions=all"</span>;</span><br><span class="line">        HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">                .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">                .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">                .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">                .version(HttpClient.Version.HTTP_2)</span><br><span class="line">                .build();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在通过http client发送构造好的HttpRequest，并获得天气查询结果"</span>);</span><br><span class="line">        HttpResponse&lt;String&gt; httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在将查询到的天气json转化为Java Bean"</span>);</span><br><span class="line">        String json = httpResponse.body();</span><br><span class="line">        ObjectMapper mapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, <span class="keyword">false</span>);</span><br><span class="line">        Weather weather = mapper.readValue(json, Weather.class);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在准备拼接字符串"</span>);</span><br><span class="line">        Forecasts forecasts = weather.forecasts.get(<span class="number">0</span>);</span><br><span class="line">        Casts today = forecasts.getCasts().get(<span class="number">0</span>);</span><br><span class="line">        Casts tomorrow = forecasts.getCasts().get(<span class="number">1</span>);</span><br><span class="line">        String result = String.format(<span class="string">"天气预报来啦~\n"</span> +</span><br><span class="line">                        <span class="string">"城市：%s\n"</span> +</span><br><span class="line">                        <span class="string">"播报时间：%s\n"</span> +</span><br><span class="line">                        <span class="string">"今日~\n"</span> +</span><br><span class="line">                        <span class="string">"日期：%s\n"</span> +</span><br><span class="line">                        <span class="string">"白天天气：%s\n"</span> +</span><br><span class="line">                        <span class="string">"夜间天气：%s\n"</span> +</span><br><span class="line">                        <span class="string">"白天温度：%s\n"</span> +</span><br><span class="line">                        <span class="string">"夜间温度：%s\n"</span> +</span><br><span class="line">                        <span class="string">"白天风向：%s\n"</span> +</span><br><span class="line">                        <span class="string">"夜间风向：%s\n"</span> +</span><br><span class="line">                        <span class="string">"风力：%s\n"</span> +</span><br><span class="line">                        <span class="string">"\n"</span> +</span><br><span class="line">                        <span class="string">"明日~\n"</span> +</span><br><span class="line">                        <span class="string">"日期：%s\n"</span> +</span><br><span class="line">                        <span class="string">"白天天气：%s\n"</span> +</span><br><span class="line">                        <span class="string">"夜间天气：%s\n"</span> +</span><br><span class="line">                        <span class="string">"白天温度：%s\n"</span> +</span><br><span class="line">                        <span class="string">"夜间温度：%s\n"</span> +</span><br><span class="line">                        <span class="string">"白天风向：%s\n"</span> +</span><br><span class="line">                        <span class="string">"夜间风向：%s\n"</span> +</span><br><span class="line">                        <span class="string">"风力：%s"</span>,</span><br><span class="line">                forecasts.getProvince() + forecasts.getCity(), forecasts.getReporttime().toString(),</span><br><span class="line">                today.getDate(), today.getDayweather(), today.getNightweather(), today.getDaytemp(), today.getNighttemp(), today.getDaywind(), today.getNightwind(), today.getDaypower(),</span><br><span class="line">                tomorrow.getDate(), tomorrow.getDayweather(), tomorrow.getNightweather(), tomorrow.getDaytemp(), tomorrow.getNighttemp(), tomorrow.getDaywind(), tomorrow.getNightwind(), tomorrow.getDaypower());</span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"拼接完毕，结果：&#123;&#125;"</span>, result);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">broadcastWeather</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, IOException, URISyntaxException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正准备向群里播报天气"</span>);</span><br><span class="line">        log.info(<span class="string">"获得天气状况（字符串）"</span>);</span><br><span class="line">        String result = generateString(httpClient);</span><br><span class="line">        Utils.sendGroupMessage(result);</span><br><span class="line">        log.info(<span class="string">"播报完毕"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Scheduled</span>(fixedRate = <span class="number">1000</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">broadcast</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, IOException, URISyntaxException </span>&#123;</span><br><span class="line">        LocalDateTime now = LocalDateTime.now();</span><br><span class="line">        <span class="keyword">if</span> (now.getHour() == <span class="number">8</span> &amp;&amp; now.getMinute() == <span class="number">0</span> &amp;&amp; now.getSecond() == <span class="number">0</span>) &#123;</span><br><span class="line">            log.info(<span class="string">"早上八点整，正准备播报天气"</span>);</span><br><span class="line">            broadcastWeather();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="新旧版本对比"><a href="#新旧版本对比" class="headerlink" title="新旧版本对比"></a>新旧版本对比</h4><p>旧版本</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gfa8s8hx0qj30lp040t8t.jpg">

<p>新版本</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjrqpxet3j30kw0mvjs5.jpg">

<h3 id="用Spring监听cqhttp上报的事件"><a href="#用Spring监听cqhttp上报的事件" class="headerlink" title="用Spring监听cqhttp上报的事件"></a>用Spring监听cqhttp上报的事件</h3><p>之前我用socket监听cqhttp的事件，但是bug很多，有一些是我百思不得其解的，后来觉得用Spring 是个好主意，果然用Spring之后就没什么问题了，Spring 天下无敌啊。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjs81bdm5j30h00ahwf4.jpg">

<p>具体做法是编写一个Controller，监听根路径的所有post事件（<code>@PostMapping(&quot;/&quot;)</code>），从Spring传入的HTTPServletRequest中读取事件信息，并利用HTTPServletResponse作出回应。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyController</span> </span>&#123;</span><br><span class="line">	<span class="meta">@PostMapping</span>(<span class="string">"/"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span></span>&#123;</span><br><span class="line">        ......</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="疫情数据查询-1"><a href="#疫情数据查询-1" class="headerlink" title="疫情数据查询"></a>疫情数据查询</h3><p>疫情数据查询时由用户主动发起的事件，所以我们需要知道用户发送了什么。cqhttp插件会将所有的事件上报到指定的端口，我们可以通过监听端口来获得事件的内容。</p>
<p>首先我们需要从用户发送的消息中判断所要查询的地区。</p>
<p>然后同样我们也需要一个查询疫情数据的api（我这儿使用的是<a href="https://lab.isaaclin.cn/nCoV/zh）。" target="_blank" rel="noopener">https://lab.isaaclin.cn/nCoV/zh）。</a></p>
<p>准备一个java bean用来接受存储数据。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot.covid19;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CovidData</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> List&lt;Result&gt; results;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot.covid19;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Result</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> String countryName;</span><br><span class="line">    <span class="keyword">public</span> String countryEnglishName;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> currentConfirmedCount;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> confirmedCount;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> curedCount;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> deadCount;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> String.format(<span class="string">"国家名称：%s，国家名称（英文）：%s，现存确诊人数：%d，累计确诊人数：%d，治愈人数：%d，死亡人数：%d"</span>,</span><br><span class="line">                countryName, countryEnglishName, currentConfirmedCount, confirmedCount, curedCount, deadCount);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后将json转为java bean并回复消息（这里利用了cqhttp的快速回复功能，跟之前的发送方式有所不同）。</p>
<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjsa2hxbvj30xd0nkdhh.jpg">

<img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1ggjsaggqloj30wl0fpwg1.jpg">

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getCovidData</span><span class="params">(HttpServletResponse response, Post post)</span> <span class="keyword">throws</span> URISyntaxException, IOException, InterruptedException </span>&#123;</span><br><span class="line">    log.info(<span class="string">"正在尝试获取地区名称"</span>);</span><br><span class="line">    String province = post.getMessage().substring(<span class="number">4</span>).strip();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    log.info(<span class="string">"正在构造HttpRequest"</span>);</span><br><span class="line">    String url = String.format(<span class="string">"https://lab.isaaclin.cn/nCoV/api/area?latest=1&amp;province=%s"</span>, province);</span><br><span class="line">    HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">            .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">            .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">            .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">            .version(HttpClient.Version.HTTP_2)</span><br><span class="line">            .build();</span><br><span class="line"></span><br><span class="line">    log.info(<span class="string">"正在用http client调用疫情数据查询api"</span>);</span><br><span class="line">    HttpResponse&lt;String&gt; httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    log.info(<span class="string">"正在将json转为Java Bean"</span>);</span><br><span class="line">    String json = httpResponse.body();</span><br><span class="line">    ObjectMapper objectMapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, <span class="keyword">false</span>);</span><br><span class="line">    CovidData covidData = objectMapper.readValue(json, CovidData.class);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    log.info(<span class="string">"正在发送消息"</span>);</span><br><span class="line">    <span class="keyword">if</span> (covidData.results.size() == <span class="number">0</span>) &#123;</span><br><span class="line">        reply(response, <span class="string">"unknown area"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        String content = covidData.results.toString();</span><br><span class="line">        reply(response, content);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="复读"><a href="#复读" class="headerlink" title="复读"></a>复读</h3><p>思路是判断用户发送的消息内容，根据消息内容改变类内的repeat变量的值，再根据repeat的值决定复读与否。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyController</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(MyController.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> repeat = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostMapping</span>(<span class="string">"/"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> IOException, URISyntaxException, InterruptedException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在获取侦测到的上报信息"</span>);</span><br><span class="line">        Post post = getPost(request);</span><br><span class="line">        <span class="keyword">if</span> (repeat) &#123;</span><br><span class="line">            log.info(<span class="string">"进入复读模式"</span>);</span><br><span class="line">            log.info(<span class="string">"开始复读"</span>);</span><br><span class="line">            Utils.sendGroupMessage(post.getMessage());</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (post.getMessage().equals(<span class="string">"退出复读模式"</span>)) &#123;</span><br><span class="line">                log.info(<span class="string">"退出复读模式"</span>);</span><br><span class="line">                repeat = <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            log.info(<span class="string">"进入一般模式"</span>);</span><br><span class="line">            <span class="keyword">if</span> (post.getMessage().equals(<span class="string">"进入复读模式"</span>)) &#123;</span><br><span class="line">                repeat = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="彩虹屁-1"><a href="#彩虹屁-1" class="headerlink" title="彩虹屁"></a>彩虹屁</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.URI;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpRequest;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpResponse;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RainbowFart</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(RainbowFart.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getRainbowFart</span><span class="params">()</span> <span class="keyword">throws</span> URISyntaxException, IOException, InterruptedException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在构造HttpRequest"</span>);</span><br><span class="line">        String url = <span class="string">"https://chp.shadiao.app/api.php"</span>;</span><br><span class="line">        HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">                .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">                .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">                .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">                .version(HttpClient.Version.HTTP_2)</span><br><span class="line">                .build();</span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在用http client调用彩虹屁api"</span>);</span><br><span class="line">        HttpResponse&lt;String&gt; httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> httpResponse.body();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (post.getMessage().startsWith(<span class="string">"夸"</span>)) &#123;</span><br><span class="line">    log.info(<span class="string">"开始彩虹屁"</span>);</span><br><span class="line">    <span class="keyword">if</span> (post.getMessage().equals(<span class="string">"夸我"</span>)) &#123;</span><br><span class="line">        replyCqHttp(response, RainbowFart.getRainbowFart());</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        String name = post.getMessage().substring(<span class="number">1</span>);</span><br><span class="line">        log.info(<span class="string">"要夸的人是&#123;&#125;"</span>, name);</span><br><span class="line">        replyCqHttp(response, RainbowFart.getRainbowFart().replace(<span class="string">"你"</span>, name).replace(<span class="string">"您"</span>, name));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现思路：调用API<a href="https://chp.shadiao.app/api.php获取彩虹屁内容并替换关键字，利用cqhttp的快速回复功能做出回复。" target="_blank" rel="noopener">https://chp.shadiao.app/api.php获取彩虹屁内容并替换关键字，利用cqhttp的快速回复功能做出回复。</a></p>
<h3 id="NMSL-1"><a href="#NMSL-1" class="headerlink" title="NMSL"></a>NMSL</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.URI;</span><br><span class="line"><span class="keyword">import</span> java.net.URISyntaxException;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpClient;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpRequest;</span><br><span class="line"><span class="keyword">import</span> java.net.http.HttpResponse;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Nmsl</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(RainbowFart.class);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> HttpClient httpClient = HttpClient.newBuilder().build();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getContent</span><span class="params">()</span> <span class="keyword">throws</span> URISyntaxException, IOException, InterruptedException </span>&#123;</span><br><span class="line">        log.info(<span class="string">"正在构造HttpRequest"</span>);</span><br><span class="line">        String url = <span class="string">"https://nmsl.shadiao.app/api.php?level=min"</span>;</span><br><span class="line">        HttpRequest httpRequest = HttpRequest.newBuilder(<span class="keyword">new</span> URI(url))</span><br><span class="line">                .header(<span class="string">"User-Agent"</span>, <span class="string">"Java HttpClient"</span>)</span><br><span class="line">                .header(<span class="string">"Accept"</span>, <span class="string">"*/*"</span>)</span><br><span class="line">                .timeout(Duration.ofSeconds(<span class="number">5</span>))</span><br><span class="line">                .version(HttpClient.Version.HTTP_2)</span><br><span class="line">                .build();</span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"正在用http client调用NMSL api"</span>);</span><br><span class="line">        HttpResponse&lt;String&gt; httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> httpResponse.body().replace(<span class="string">" "</span>, <span class="string">""</span>).replace(<span class="string">"\n"</span>, <span class="string">""</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (post.getMessage().startsWith(<span class="string">"骂"</span>)) &#123;</span><br><span class="line">    log.info(<span class="string">"开始nmsl"</span>);</span><br><span class="line">    <span class="keyword">if</span> (post.getMessage().equals(<span class="string">"骂我"</span>)) &#123;</span><br><span class="line">        replyCqHttp(response, Nmsl.getContent());</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        String name = post.getMessage().substring(<span class="number">1</span>);</span><br><span class="line">        replyCqHttp(response, Nmsl.getContent().replace(<span class="string">"您"</span>, name).replace(<span class="string">"你"</span>, name));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现思路和彩虹屁完全一致。</p>
<h3 id="学习-1"><a href="#学习-1" class="headerlink" title="学习"></a>学习</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> eternal.fire.springbootrobot;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> eternal.fire.springbootrobot.controller.MainController;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Arrays;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Learn</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Map&lt;String, String&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger log = LoggerFactory.getLogger(Learn.class);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">learn</span><span class="params">(String message)</span> </span>&#123;</span><br><span class="line">        String[] args = message.split(<span class="string">" "</span>);</span><br><span class="line">        log.info(<span class="string">"获取到的内容是&#123;&#125;"</span>, Arrays.toString(args));</span><br><span class="line">        <span class="keyword">if</span> (args.length &lt; <span class="number">3</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        map.put(args[<span class="number">1</span>], args[<span class="number">2</span>]);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (post.getMessage().startsWith(<span class="string">"跟我学"</span>)) &#123;</span><br><span class="line">    log.info(<span class="string">"开始学习"</span>);</span><br><span class="line">    <span class="keyword">int</span> ans = Learn.learn(post.getMessage());</span><br><span class="line">    <span class="keyword">if</span> (ans == -<span class="number">1</span>) &#123;</span><br><span class="line">        replyCqHttp(response, <span class="string">"???"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ans == <span class="number">0</span>) &#123;</span><br><span class="line">        replyCqHttp(response, <span class="string">"呐，我学会了哟，你呢w"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (Learn.map.containsKey(post.getMessage())) &#123;</span><br><span class="line">        replyCqHttp(response,Learn.map.get(post.getMessage()));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现思路：Learn类内维护一个Map，用来存储键值对。每次接收到消息都去map里找是否存在相应的键值对。</p>
<p>要想数据长生不老，可以把数据写到文件里，或者使用数据库，否则每次应用重启之后，数据都会消失。</p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><p>Arina：<a href="http://47.98.252.1:7000/arina" target="_blank" rel="noopener">http://47.98.252.1:7000/arina</a></p>
<p>Arina的github（可以看我的源代码）：<a href="https://github.com/carpediemtal/Robot" target="_blank" rel="noopener">https://github.com/carpediemtal/Robot</a></p>
<p>cqhttp官方文档：<a href="https://cqhttp.cc/docs/4.15/#/" target="_blank" rel="noopener">https://cqhttp.cc/docs/4.15/#/</a></p>
<p>通过wine在docker中运行酷q：<a href="https://github.com/CoolQ/docker-wine-coolq" target="_blank" rel="noopener">https://github.com/CoolQ/docker-wine-coolq</a></p>
<p>图灵机器人：<a href="http://www.turingapi.com/" target="_blank" rel="noopener">http://www.turingapi.com/</a></p>
<p>有意思的API：<a href="https://shadiao.app/" target="_blank" rel="noopener">https://shadiao.app/</a></p>
<h2 id="———————未完待续———————"><a href="#———————未完待续———————" class="headerlink" title="———————未完待续———————"></a>———————未完待续———————</h2>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>赠人玫瑰，手有余香</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Ming WeChat Pay">
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Ming Alipay">
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/05/28/Spring-Boot-表单输入验证/" rel="next" title="Spring Boot:表单输入验证">
                <i class="fa fa-chevron-left"></i> Spring Boot:表单输入验证
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/06/01/将IntelliJ-Idea的项目发布到github/" rel="prev" title="将IntelliJ Idea的项目发布到github">
                将IntelliJ Idea的项目发布到github <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/arina.jpg" alt="Ming">
            
              <p class="site-author-name" itemprop="name">Ming</p>
              <p class="site-description motion-element" itemprop="description">Come on, check me out!</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">153</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/carpediemtal" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mail:674602921@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="qq:674602921" target="_blank" title="QQ">
                      
                        <i class="fa fa-fw fa-qq"></i>QQ</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="overwatchID:SEKAI#51158" target="_blank" title="Overwatch">
                      
                        <i class="fa fa-fw fa-gamepad"></i>Overwatch</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.treasurew.com/" title="treasurew" target="_blank">treasurew</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#QQ聊天机器人-教程向"><span class="nav-number">1.</span> <span class="nav-text">QQ聊天机器人-教程向</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#功能："><span class="nav-number">1.1.</span> <span class="nav-text">功能：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#发送以-为前缀的消息可以触发图灵机器人的功能，这些功能包含但不限于："><span class="nav-number">1.1.0.1.</span> <span class="nav-text">发送以#为前缀的消息可以触发图灵机器人的功能，这些功能包含但不限于：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#不需要-前缀能对一些特定的语句做出反应"><span class="nav-number">1.1.0.2.</span> <span class="nav-text">不需要#前缀能对一些特定的语句做出反应</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#可以在群里-其他人或者禁言（需要管理员权限）"><span class="nav-number">1.1.0.3.</span> <span class="nav-text">可以在群里@其他人或者禁言（需要管理员权限）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#null"><span class="nav-number">1.1.0.4.</span> <span class="nav-text"></span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#可以通过接口向指定的群手动发送消息"><span class="nav-number">1.1.0.5.</span> <span class="nav-text">可以通过接口向指定的群手动发送消息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#定时天气播报"><span class="nav-number">1.1.0.6.</span> <span class="nav-text">定时天气播报</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#定时晚安"><span class="nav-number">1.1.0.7.</span> <span class="nav-text">定时晚安</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#记录清醒时长"><span class="nav-number">1.1.0.8.</span> <span class="nav-text">记录清醒时长</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#疫情数据查询"><span class="nav-number">1.1.0.9.</span> <span class="nav-text">疫情数据查询</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#复读机"><span class="nav-number">1.1.0.10.</span> <span class="nav-text">复读机</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#彩虹屁"><span class="nav-number">1.1.0.11.</span> <span class="nav-text">彩虹屁</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#NMSL"><span class="nav-number">1.1.0.12.</span> <span class="nav-text">NMSL</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#学习"><span class="nav-number">1.1.0.13.</span> <span class="nav-text">学习</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Arina的个人页面"><span class="nav-number">1.1.0.14.</span> <span class="nav-text">Arina的个人页面</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#需要的技能或工具："><span class="nav-number">1.2.</span> <span class="nav-text">需要的技能或工具：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本项目基于："><span class="nav-number">1.3.</span> <span class="nav-text">本项目基于：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本fw使用的开发平台："><span class="nav-number">1.4.</span> <span class="nav-text">本fw使用的开发平台：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#酷q和cqhttp介绍"><span class="nav-number">1.5.</span> <span class="nav-text">酷q和cqhttp介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#酷q"><span class="nav-number">1.5.1.</span> <span class="nav-text">酷q</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cqhttp"><span class="nav-number">1.5.2.</span> <span class="nav-text">cqhttp</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#购买服务器"><span class="nav-number">1.6.</span> <span class="nav-text">购买服务器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务器开放端口"><span class="nav-number">1.7.</span> <span class="nav-text">服务器开放端口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#酷q在linux环境下的运行"><span class="nav-number">1.8.</span> <span class="nav-text">酷q在linux环境下的运行</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取并配置图灵机器人api-key"><span class="nav-number">1.9.</span> <span class="nav-text">获取并配置图灵机器人api key</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#核心：cqhttp插件的使用（java）"><span class="nav-number">1.10.</span> <span class="nav-text">核心：cqhttp插件的使用（java）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装"><span class="nav-number">1.10.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#API"><span class="nav-number">1.10.2.</span> <span class="nav-text">API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#发送qq消息"><span class="nav-number">1.10.3.</span> <span class="nav-text">发送qq消息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#禁言群用户"><span class="nav-number">1.10.4.</span> <span class="nav-text">禁言群用户</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定时发送消息"><span class="nav-number">1.10.5.</span> <span class="nav-text">定时发送消息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定时晚安功能"><span class="nav-number">1.10.6.</span> <span class="nav-text">定时晚安功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定时天气播报-1"><span class="nav-number">1.10.7.</span> <span class="nav-text">定时天气播报</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#旧版本代码"><span class="nav-number">1.10.7.1.</span> <span class="nav-text">旧版本代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#新版本代码"><span class="nav-number">1.10.7.2.</span> <span class="nav-text">新版本代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#新旧版本对比"><span class="nav-number">1.10.7.3.</span> <span class="nav-text">新旧版本对比</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用Spring监听cqhttp上报的事件"><span class="nav-number">1.10.8.</span> <span class="nav-text">用Spring监听cqhttp上报的事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#疫情数据查询-1"><span class="nav-number">1.10.9.</span> <span class="nav-text">疫情数据查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复读"><span class="nav-number">1.10.10.</span> <span class="nav-text">复读</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#彩虹屁-1"><span class="nav-number">1.10.11.</span> <span class="nav-text">彩虹屁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#NMSL-1"><span class="nav-number">1.10.12.</span> <span class="nav-text">NMSL</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#学习-1"><span class="nav-number">1.10.13.</span> <span class="nav-text">学习</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考资料"><span class="nav-number">1.11.</span> <span class="nav-text">参考资料</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#———————未完待续———————"><span class="nav-number">1.12.</span> <span class="nav-text">———————未完待续———————</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ming</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">64.9k</span>
  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
